//
//  RHBlockDetailVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/10/26.
//

#import "RHBlockDetailVC.h"
#import "RHCommonDataCell.h"
#import "SYChartTool.h"

@interface RHBlockDetailVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSArray *dataArr;

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSMutableDictionary *dataDic;
@end

@implementation RHBlockDetailVC
-(NSMutableDictionary *)dataDic
{
    if(!_dataDic){
        _dataDic = [NSMutableDictionary dictionary];
    }
    return _dataDic;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"遥测量".rh_localized;
    self.view.backgroundColor = CFTabViewBgColor;
    [self setupUI];
    [self getPCSData];
}


-(void)setupUI
{
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"Dev_master_measurement"];
    self.dataArr = [NSArray yy_modelArrayWithClass:[RHDevEndPointDataModel class] json:arr];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = CFTabViewBgColor;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonNormalCell];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonStatusCell];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonIndicatorCell];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonProgressCell];
    [_tableView setBackgroundColor:UIColor.whiteColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.layer.cornerRadius = 8;
    _tableView.layer.masksToBounds = YES;
    _tableView.showsVerticalScrollIndicator = NO;
    
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        [weakSelf getPCSData];
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    RHDevEndPointDataModel *section_model = self.dataArr[section];
    return section_model.infoArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 35;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    RHDevEndPointDataModel *emsModel = self.dataArr[section];
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 60)];
    headView.backgroundColor = CFTabViewBgColor;
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 10, kUI_WINDOW_W-30, 50)];
    [headView addSubview:bgView];
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    bgView.backgroundColor = [UIColor whiteColor];
    UIImageView *icon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:emsModel.icon]];
    [bgView addSubview:icon];
    
    UILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.font = kSYSTEMFONT(15);
    titleLab.textColor = kColorRGB(0, 0, 0);
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.text = emsModel.title;
    [bgView addSubview:titleLab];
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX(@"EBEDF0");
    [bgView addSubview:line];
    
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(20, 20)));
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(icon.mas_right).offset(15);
        make.centerY.equalTo(icon);
     }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(1);
        make.bottom.mas_offset(-5);
    }];
   return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 20;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 20)];
    footer.backgroundColor = CFTabViewBgColor;
    UIView *subView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, footer.width-30, 10)];
    subView.backgroundColor = [UIColor whiteColor];
    subView.layer.cornerRadius = 8;
    subView.layer.masksToBounds = YES;
    subView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    [footer addSubview:subView];
    return footer;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHCommonDataCell *cell;
    RHDevEndPointDataModel *section_model = self.dataArr[indexPath.section];
    RHDevDataModel *dataModel = section_model.infoArr[indexPath.row];
    NSInteger celltype = dataModel.type ;
    if(celltype == CommonCellTypeNormal){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonNormalCell];
    }else if (celltype == CommonCellTypeStatus){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonStatusCell];
    }else if (celltype == CommonCellTypeIndicator){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonIndicatorCell];
    }else if (celltype == CommonCellTypeProgress){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonProgressCell];
    }
    cell.dataModel = dataModel;
    return cell;
}

#pragma mark ------- network -----

//获取pcs数据
-(void)getPCSData
{
 
    [QMUITips showLoadingInView:self.view];
    
    NSArray *pcsParas = @[@"Pcs_TtlACAtvPwr",
                          @"Pcs_TtlACRtvPwr",
                          @"Pcs_TtlACaptPwr",
                          @"Pcs_TtlACAtvPwr",
                          @"Pcs_TtlACPF"
    ];
    
    NSDictionary *para = @{@"deviceId":self.devModel.deviceId,
                           @"endpointTypeCode":@"PCS",
                           @"keyCodes":pcsParas,
                           @"endpointSn":ValidNullData(self.curEmsModel.pcsSn)
    };
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
              
                self.dataDic = [NSMutableDictionary dictionaryWithDictionary:request.responseObject[@"data"]];
                [self getMasterData];
               
                
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

-(void)getMasterData
{
    [QMUITips showLoadingInView:self.view];
    NSArray *masterParas = @[@"Mtr_RSOC",
                             @"Mtr_SOC",
                             @"Mtr_SOH",
                             @"Mtr_SysFlt2_3805",
                             @"Mtr_MaxChgCur",
                             @"Mtr_MaxChgCur",
                             @"Mtr_MaxDischgCur",
                             @"Mtr_HV",
                             @"Mtr_LV",
                             @"Mtr_HT",
                             @"Mtr_LT",
                             @"Mtr_TV",
                             @"Mtr_Cur"
    ];
    
    NSDictionary *para = @{@"deviceId":self.devModel.deviceId,
                           @"endpointTypeCode":@"Master",
                           @"keyCodes":masterParas,
                           @"endpointSn":self.curMaterModel.sn
    };
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                [self.dataDic addEntriesFromDictionary:request.responseObject[@"data"]];
                [self refreshData:self.dataDic];
                
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}


-(void)refreshData:(NSDictionary *)dic{
    //电芯最高压差(Mtr_HV-Mtr_LV)
    __block RHDevDataModel *cell_v_model ;
    //电芯最高温差(Mtr_HT - Mtr_LT)
    __block RHDevDataModel *cell_t_model ;
    //直流功率(Mtr_TV * Mtr_Cur)
    __block RHDevDataModel *p_model ;
    
    [self.dataArr enumerateObjectsUsingBlock:^(RHDevEndPointDataModel  *_Nonnull masterModel, NSUInteger idx, BOOL * _Nonnull stop) {
        masterModel.data = dic;
        //直流功率
        [masterModel.infoArr enumerateObjectsUsingBlock:^(RHDevDataModel  *_Nonnull dataModel, NSUInteger idx, BOOL * _Nonnull stop) {
            if([dataModel.alias isEqualToString:@"电芯最高压差"]){
                cell_v_model = dataModel;
            }
            if([dataModel.alias isEqualToString:@"电芯最高温差"]){
                cell_t_model = dataModel;
            }
            if([dataModel.alias isEqualToString:@"直流功率"]){
                p_model = dataModel;
            }
            
            
        }];
    }];
    //直流功率
    double p_value = [ValidNullData(dic[@"Mtr_TV"]) doubleValue] * [ValidNullData(dic[@"Mtr_Cur"]) doubleValue];
    p_model.content = [[NSNumber numberWithDouble:p_value] twoDecimalPlacesWithoutRounding];
    
    //电芯最高压差(Mtr_HV - Mtr_LV)
    double v_value = [ValidNullData(dic[@"Mtr_HV"]) doubleValue] - [ValidNullData(dic[@"Mtr_LV"]) doubleValue];
    cell_v_model.content = [[NSNumber numberWithDouble:v_value] twoDecimalPlacesWithoutRounding];
    
    //电芯最高温差(Mtr_HT - Mtr_LT)
    double t_value = [ValidNullData(dic[@"Mtr_HT"]) doubleValue] - [ValidNullData(dic[@"Mtr_LT"]) doubleValue];
    cell_t_model.content = [[NSNumber numberWithDouble:t_value] twoDecimalPlacesWithoutRounding];
    
    [self.tableView reloadData];
}
@end
